package com.duoduo.mcc;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SyncSimpleTest {
	public static void main(String[] args) {
		startProcess("1118000", "消费者1", 2000);
		startProcess("1118000", "消费者2", 3000);
		startProcess("1118000", "消费者3", 5000);

		startProcess("1118001", "消费者4", 2000);
		startProcess("1118001", "消费者5", 3000);
		startProcess("1118001", "消费者6", 5000);
	}

	private static void startProcess(String key, String consumer, long waitTime) {
		MyProcessThread pt = new MyProcessThread(key, consumer, waitTime);
		Thread t = new Thread(pt);
		t.start();
	}
}


class MyProcessThread implements Runnable {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private String key;
	private String consumer;
	private long waitTime;
	private Random random;

	public MyProcessThread(String key, String consumer, long waitTime) {
		this.key = key;
		this.consumer = consumer;
		this.waitTime = waitTime;

		this.random = new Random(System.currentTimeMillis());
	}

	public void doSomething(long time) {
		logger.info("{} 开始处理 {} 对应的消息", consumer, key);

		try {
			Thread.sleep(time);
		} catch (Exception e) {

		}
		logger.info("{} 完成处理 {} 对应的消息", consumer, key);
	}

	public void run() {
		while (true) {
			logger.info("{} 请求处理 {} >>>>>>", consumer, key);
			synchronized (key) {
				logger.info("{} 开始执行 {} 对应的消息", consumer, key);
				doSomething(waitTime);
			}

			try {
				Thread.sleep(200 + random.nextInt(200));
			} catch (Exception e) {

			}
		}
	}

}
